/**
 * Q:写一个events，backbone或者jquery，包括on、off、once、trigger
 */

class EventEmitter {
  constructor () {
    this.__events = {}
  }
  on (event, listener) {
    (this.__events[event] || (this.__events[event] = [])).push(listener);
  }
  off (event, listener) {
    let listeners;
    if (!this.__events || !(listeners = this.__events[event])) {
      return this;
    }
    listeners.forEach((fn, i) => {
      if (fn === listener) {
        listeners.splice(i, 1);
      }
    })
    if (listeners.length === 0) {
      delete this.__events[event];
    }
    return this;
  }
  once (event, listener) {
    let fn = (...arg) => {
      this.off(event, fn);
      listener.apply(this, arg);
    }
    this.on(event, fn);
    return this;
  }
  trigger (event, ...args) {
    let listeners;
    if (!this.__events || !(listeners = this.__events[event])) {
      return this;
    }
    listeners.forEach(fn => fn.apply(this, args));
    return this;
  }
}

var emit = new EventEmitter();
function one(msg) {
  console.log('one', msg);
}
function two(msg) {
  console.log('two', msg);
}
function three(msg) {
  console.log('three', msg);
}
emit.on('say', one);
emit.on('say', two);

emit.once('say', () => three.call(null, 1,2,3,4,5));

emit.trigger('say', 'hello Emit');
emit.trigger('say', 'hello');


